package com.example.aihub.controller;

import com.example.aihub.entity.User;
import com.example.aihub.exception.ResourceNotFoundException;
import com.example.aihub.service.UserService;
// 添加UserProfileRequest的导入
import com.example.aihub.dto.UserProfileRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

// 添加以下导入
import com.example.aihub.service.FileUploadService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;
    private final FileUploadService fileUploadService;

    @Autowired
    public UserController(UserService userService, FileUploadService fileUploadService) {
        this.userService = userService;
        this.fileUploadService = fileUploadService;
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody RegisterRequest registerRequest) {
        try {
            User user = userService.registerUser(
                    registerRequest.getUsername(),
                    registerRequest.getEmail(),
                    registerRequest.getPassword()
            );
            return new ResponseEntity<>(new ApiResponse(true, "注册成功", user), HttpStatus.CREATED);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }

    // 获取用户信息
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        try {
            User user = userService.findById(id);
            return ResponseEntity.ok(new ApiResponse(true, "获取用户信息成功", user));
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.NOT_FOUND);
        }
    }

    // 添加个人简介更新端点（匹配前端调用）
    // 在UserController类中找到updateCurrentUserProfile方法并修改
    // 修改updateCurrentUserProfile方法，使用userService而不是userRepository
    @PutMapping("/profile")
    public ResponseEntity<?> updateCurrentUserProfile(@RequestBody UserProfileRequest profileRequest) {
        try {
            // 获取当前登录用户
            String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));
    
            // 更新用户资料
            if (profileRequest.getBio() != null) {
                user.setBio(profileRequest.getBio());
            }
            if (profileRequest.getAvatar() != null) {
                user.setAvatar(profileRequest.getAvatar());
            }
            // 添加新字段的更新
            if (profileRequest.getPhoneNumber() != null) {
                user.setPhoneNumber(profileRequest.getPhoneNumber());
            }
            if (profileRequest.getBirthDate() != null) {
                user.setBirthDate(profileRequest.getBirthDate());
            }
            if (profileRequest.getGender() != null) {
                user.setGender(profileRequest.getGender());
            }
            if (profileRequest.getLocation() != null) {
                user.setLocation(profileRequest.getLocation());
            }
            
            // 使用userService而不是userRepository来保存用户
            User updatedUser = userService.updateUser(user);
            
            return ResponseEntity.ok(new ApiResponse(true, "更新资料成功", updatedUser));
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }

    // 请求体类
    static class RegisterRequest {
        private String username;
        private String email;
        private String password;

        // Getters and Setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    // 删除UserController内部的UserProfileRequest静态类
    // 将以下代码删除
    /*
    static class UserProfileRequest {
        private String bio;
        private String avatar;
    
        // Getters and Setters
        public String getBio() { return bio; }
        public void setBio(String bio) { this.bio = bio; }
        public String getAvatar() { return avatar; }
        public void setAvatar(String avatar) { this.avatar = avatar; }
    }
    */

    // 响应体类
    static class ApiResponse {
        private boolean success;
        private String message;
        private Object data;

        public ApiResponse(boolean success, String message, Object data) {
            this.success = success;
            this.message = message;
            this.data = data;
        }

        // Getters and Setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        public Object getData() { return data; }
        public void setData(Object data) { this.data = data; }
    }
    // 添加头像上传端点
    // 头像上传功能
    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 获取当前登录用户
            String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));
    
            // 上传文件
            String filePath = fileUploadService.uploadFile(file);
    
            // 更新用户头像
            User updatedUser = userService.updateUserProfile(user.getId(), null, filePath);
    
            return ResponseEntity.ok(new ApiResponse(true, "头像上传成功", updatedUser.getAvatar()));
        } catch (IOException e) {
            return new ResponseEntity<>(new ApiResponse(false, "头像上传失败: " + e.getMessage(), null), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    // 添加关注用户的API端点
    @PostMapping("/follow/{userId}")
    public ResponseEntity<?> followUser(@PathVariable Long userId) {
        try {
            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            
            // 检查用户是否已经登录
            if (auth == null || !auth.isAuthenticated() || auth.getPrincipal() instanceof String) {
                // 如果未登录，返回401未授权状态码
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            // 安全地转换为UserDetails对象
            String username = ((UserDetails) auth.getPrincipal()).getUsername();
            User follower = userService.findByUsername(username)
                    .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));
            
            // 获取被关注的用户
            User followed = userService.findById(userId);
            
            // 执行关注操作
            userService.followUser(follower, followed);
            
            return ResponseEntity.ok(new ApiResponse(true, "关注成功", null));
        } catch (ResourceNotFoundException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.NOT_FOUND);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }
    
    // 添加取消关注用户的API端点
    @DeleteMapping("/follow/{userId}")
    public ResponseEntity<?> unfollowUser(@PathVariable Long userId) {
        try {
            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            
            // 检查用户是否已经登录
            if (auth == null || !auth.isAuthenticated() || auth.getPrincipal() instanceof String) {
                // 如果未登录，返回401未授权状态码
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            // 安全地转换为UserDetails对象
            String username = ((UserDetails) auth.getPrincipal()).getUsername();
            User follower = userService.findByUsername(username)
                    .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));
            
            // 获取被取消关注的用户
            User followed = userService.findById(userId);
            
            // 执行取消关注操作
            userService.unfollowUser(follower, followed);
            
            return ResponseEntity.ok(new ApiResponse(true, "取消关注成功", null));
        } catch (ResourceNotFoundException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.NOT_FOUND);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }
    
    // 检查是否关注了某个用户
    @GetMapping("/follow/check/{userId}")
    public ResponseEntity<?> checkFollowing(@PathVariable Long userId) {
        try {
            // 获取当前登录用户
            String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
            User follower = userService.findByUsername(username)
                    .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));
            
            // 获取目标用户
            User followed = userService.findById(userId);
            
            // 检查是否关注
            boolean isFollowing = userService.isFollowing(follower, followed);
            
            return ResponseEntity.ok(new ApiResponse(true, "查询成功", isFollowing));
        } catch (RuntimeException e) {
            return new ResponseEntity<>(new ApiResponse(false, e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }
}

